<template>
  <div class="box">
    <div id="main" ref="main"></div>
    <div id="macd"></div>
    <div class="data">
      <span>{{ theData.date.time + "--" + theData.date.week }}</span
      >&nbsp; <span>最高：{{ theData.heightPrice }}</span
      >&nbsp; <span>最低：{{ theData.lowP }}</span
      >&nbsp;
      <span>当前:{{ theData.nowPrice }}</span>
    </div>
  </div>
</template>

<script setup>
import {
  onMounted,
  onUnmounted,
  reactive,
  watchEffect,
  getCurrentInstance,
  nextTick,
  watch,

} from "vue";
import Qs from "qs";
import { getBin } from "../../api/stock";
import { useInfoStore } from "../../store";

const userInfo = useInfoStore();
const _this = getCurrentInstance();
const test = async () => {
  await nextTick();
  watch(
    () => userInfo.navFlag,
    (newValue, oldValue) => {
      // const mainWidth = _this.ctx.$refs.main.offsetWidth
      // console.log()
      // console.log(newValue);
      // initEcharts()
    },
    { deep: true }
  );
};

const theData = reactive({
  src: null,
  heightPrice: 0,
  lowP: 0,
  yesClose: 0,
  nowPrice: null,
  result: [],
  zxlist: [],
  theLastPrice: 0,
  date: {
    time: "",
    week: "",
  },
});

const { proxy } = getCurrentInstance();
onMounted(async () => {
  await updata();
  // console.log(theData.yesClose);
  initMacd()
  initEcharts();
  window.addEventListener("resize", () => {
    nextTick(() => {
      myChart.resize();
      macdCharts.resize();
    });
  });
  // myChart.resize();
});

//更新数据
const updata = () => {
  return new Promise(async (res, rej) => {
    var params = Qs.stringify({
      "c.funcno": "20001",
      "c.version": "1",
      "c.stock_code": "000300",//中正300
      "c.market": "SH",
      "c.start": "0",
      "c.cfrom": "H5",
      "c.tfrom": "PC",
      "c.CHANNEL": "",
    });
    const { data } = await getBin(params);
    //  console.log(data)
    theData.src = data;
    theData.heightPrice = data.HIGHPRICE / 1000;
    theData.lowP = data.LOWPRICE / 1000;
    //重置数据
    theData.result = [];
    theData.zxlist = [];
    //新造数据
    const BINDATA = JSON.parse(data.BINDATA);
    theData.result = BINDATA.results;
    theData.yesClose = BINDATA.yesClose;
    theData.nowPrice = theData.result.slice(-1)[0];
    //价格数据
    theData.result.forEach((el) => {
      theData.zxlist.push(el[1]);
    });
    theData.zxlist.unshift(BINDATA.yesClose);
    //每次更新也重新显示时间
    getTime();
    constructCandelbar();
    res(1);
  });
};
//时间
function getTime() {
  const t = proxy.timeMaker.publicTimestampDate(new Date().getTime());
  const week = proxy.timeMaker.publicWeekDate(t);
  theData.date.time = t;
  theData.date.week = week;
  // console.log(theData);
  //判断时间 决定是否打开请求开关，请求开关提前开盘前五秒打开
}

const workClick = () => {
  const clock = theData.date.time.slice(-8);
  if (
    (clock > "09:30:00" && clock < "11:30:00") ||
    (clock > "13:00:00" && clock < "15:01:00")
  ) {
    return true;
  } else {
    return false;
  }
};
//组合数据
const candelData = reactive({
  minArray: [], //每分钟数据总和
  kLine: [], //二元数组存[open,close,height，low,time]
  jiaquan: [], //k线的加权收盘价
  timeLine:[]
});

//做k线图的数据（实时更新）
const constructCandelbar = () => {
  const s = theData.date.time.slice(-2);
  if (workClick()) {
    if (s == "00") {
      candelData.minArray = [];
    }
    candelData.minArray.push(theData.nowPrice[1]); //每秒都要更新minArray
    //在minArray中 取出[open,close,height，low,time]
    let kLine = [
      candelData.minArray[0],
      candelData.minArray.slice(-1)[0],
      Math.max(...candelData.minArray),
      Math.min(...candelData.minArray),
      theData.date.time.slice(-8),
    ];
    //加权平均
    const [op, cp, hp, lp] = kLine;
    // let jiaquan  = (2 * cp + hp + lp) / 4
    //当00 新开始时候推新的k线，其他情况则替换最后一个
    if (s == "00") {
      candelData.kLine.push(kLine);
      candelData.timeLine.push(kLine[4])
      //这里没有除以4 注意后期调整参数
      candelData.jiaquan.push(2 * cp + hp + lp) / 4;
      // console.log(candelData.jiaquan);
    } else {
      candelData.kLine.splice(-1, 1, kLine);
      candelData.jiaquan.splice(-1, 1, 2 * cp + hp + lp) / 4;
    }
    macdConstruc()
  }
};
const macdData = reactive({
  ema12: [],
  ema26: [],
  macd: [],
});

const macdConstruc=()=>{
  seEma12()
  setEma26()
  setMACD()
  initMacd()
}
//12
const seEma12 = () => {
  macdData.ema12 = [];
  candelData.jiaquan.forEach((el, index) => {
    if (index == 0) {
      macdData.ema12[0] = el;
    } else if (index !== 0) {
      macdData.ema12[index] = (2 / 13) * el + (11 / 13) * macdData.ema12[index - 1];
      //前一日EMA12 X 11/13 + 今日收盘 X 2/13
    }
  });
  // console.log(111,macdData.ema12)
};
//26
const setEma26 = () => {
  macdData.ema26 = [];
  candelData.jiaquan.forEach((el, index) => {
    if (index == 0) {
      macdData.ema26[0] = el;
    }
    if (index != 0) {
      macdData.ema26[index] = (2 / 27) * el + (25 / 27) * macdData.ema26[index - 1];
    }
  });
  // console.log(222,macdData.ema26)

};
//12-26
const setMACD = () => {
  macdData.macd = [];
  macdData.ema12.forEach((el, index, slef) => {
    macdData.macd.push((el - macdData.ema26[index])*100000);
  });
};

var macdCharts;
const initMacd = () => {
  macdCharts = null;
  macdCharts = proxy.echarts.init(document.getElementById("macd"));
  watchEffect(() => {
    if(macdData.ema12 )
    var option;
    option = {
      title: {
        text: "MACD",
        y: 'bottom',
      },
      legend: {
        y: 'bottom',
        data: ["macd", "ema12", "ema26"],
      },
      toolbox: {
        y: 'bottom',
        feature: {
          magicType: {
            type: ["stack"],
          },
          dataView: {},
          saveAsImage: {
            pixelRatio: 2,
          },
        },
      },
      tooltip: {},
      xAxis: {
        data: candelData.timeLine,
        splitLine: {
          // show: false,
        },
      },
      yAxis: [{}, {}],
      series: [
        {
          name: "macd",
          type: "bar",
          data: macdData.macd,
          emphasis: {
            focus: "series",
          },
          animationDelay: (idx) => {
            return idx * 10;
          },
        },

        {
          name: "ema12",
          type: "line",
          // yAxisIndex: 2,
          data: macdData.ema12,
        },
        {
          name: "ema26",
          type: "line",
          // yAxisIndex: 2,
          data: macdData.ema26,
        },
      ],
      animationEasing: "elasticOut",
      animationDelayUpdate: (idx) => {
        return idx * 5;
      },
    };
    option && macdCharts.setOption(option);
  });
};
//定时请求数据
let timer
function updateClock(){
  timer!=null && clearTimeout(timer)
  workClick() && updata();
  timer=setTimeout(()=>{
    updateClock()
  },2000)
}
updateClock()

onUnmounted(() => {
  clearTimeout(timer)
});
//指数表
var myChart;
const initEcharts = () => {
  myChart = null;
  myChart = proxy.echarts.init(document.getElementById("main"));
  watchEffect(() => {
    var option;
    //价格折线图配置
    option = {
      xAxis: {
        type: "category",
        data: theData.zxlist,
      },
      legend: {
        bottom: "auto",
      },
      yAxis: {
        type: "value",
        max: theData.heightPrice,
        min: theData.lowP * 0.99,
        axisLabel: {
          formatter(value, index) {
            let list = [];
            let num = Math.floor(
              ((value - theData.yesClose) * 1000) / theData.yesClose
            );
            // console.log(num)
            list.push(num / 10 + "%");
            return list;
          },
        },
      },
      series: [
        {
          data: theData.zxlist,
          type: "line",
        },
      ],
    };
    option && myChart.setOption(option);
  });
};
</script>

<style scoped>
.box {
  position: relative;
  height: 100%;
  width: 100%;
  /* display: flex; */
}
#main {
  height: 100%;
  width: 50%;
  left: 50%;
  background-color: rgb(143, 144, 145);
  position: absolute;
}
#macd {
  height:100%;
  width: 50%;
  background-color: rgb(167, 168, 171);
  position: absolute;
}
.data {
  position: absolute;
  background-color: rgba(161, 154, 154, 0.44);
  margin: 10px 15px;
  padding: 5px 10px;
  border-radius: 10px;
}
.data:hover {
  background-color: rgba(176, 159, 159, 0.68);
  cursor: pointer;
}
</style>
